package com.tsn.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileUtils {
    /**
     *
     * @param fileName
     *      文件名
     * @param downloadName
     *      下载的名字
     * @param response
     */
    public static void downloadFile(String fileName, String downloadName, HttpServletResponse response){
        try {
            response.setContentType("octets/stream");
            response.addHeader("Content-Type", "text/html; charset=utf-8");
            String downLoadName = new String(downloadName.getBytes("gbk"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);

            FileInputStream fileInputStream = new FileInputStream(fileName);
            OutputStream out = response.getOutputStream();
            int i = 0;
            while ((i = fileInputStream.read()) != -1) {
                out.write(i);
            }
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file
     *            文件
     * @param radomfileName
     *            保存文件名
     * @param materialFilePath
     *            保存路径
     * @return
     */
    public static boolean fileUpload(MultipartFile file, String radomfileName,
                                     String materialFilePath) {
        boolean flag = true;
        File baseFile = new File(materialFilePath);
        File trainFile = new File(baseFile, radomfileName);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        try {
            file.transferTo(trainFile);
        } catch (IllegalStateException e) {
            flag = false;
        } catch (IOException e) {
            flag = false;
        }// 保存文件
        return flag;
    }
}
